package com.example.servlet;



import com.example.dao.BookTransactionDao;

import com.example.entity.BookTransaction;
import com.example.entity.BookTransaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/cart/*")
public class CartServlet extends HttpServlet {
    private BookTransactionDao transactionDao = new BookTransactionDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        if ("/list".equals(action)) {
            showCart(request, response);
        } else if ("/add".equals(action)) {
            addToCart(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        switch (action) {
            case "/remove":
                removeFromCart(request, response);
                break;
            case "/checkout":
                checkout(request, response);
                break;
        }
    }


    private void showCart(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 添加调试信息
            System.out.println("Showing cart for student ID: " + request.getSession().getAttribute("studentId"));

            int studentId = Integer.parseInt(request.getSession().getAttribute("studentId").toString());
            List<BookTransaction> transactions = transactionDao.getTransactionsByStudentId(studentId);

            // 打印查询到的交易记录
            System.out.println("Found " + transactions.size() + " transactions");
            for (BookTransaction t : transactions) {
                System.out.println("Transaction: " + t.getBookName() + " - " + t.getTransactionPrice());
            }

            // 计算总价
            BigDecimal total = transactions.stream()
                    .map(BookTransaction::getTransactionPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            request.setAttribute("transactions", transactions);
            request.setAttribute("total", total);
            request.getRequestDispatcher("/cart.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    private void addToCart(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        try {
            // 添加调试信息
            System.out.println("Session ID: " + request.getSession().getId());
            System.out.println("Student ID from session: " + request.getSession().getAttribute("studentId"));

            // 从session获取studentId
            Object studentIdObj = request.getSession().getAttribute("studentId");
            if (studentIdObj == null) {
                System.out.println("Student ID is null in session");
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取请求参数
            String bookId = request.getParameter("bookId");
            String bookName = request.getParameter("bookName");
            String price = request.getParameter("price");

            System.out.println("Book ID: " + bookId);
            System.out.println("Book Name: " + bookName);
            System.out.println("Price: " + price);

            BookTransaction transaction = new BookTransaction();
            transaction.setStudentId(Integer.parseInt(studentIdObj.toString()));
            transaction.setBookId(Integer.parseInt(bookId));
            transaction.setBookName(bookName);
            transaction.setTransactionPrice(new BigDecimal(price));

            transactionDao.addTransaction(transaction);
            response.sendRedirect(request.getContextPath() + "/cart/list");

        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.out.println("Error in addToCart: " + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    private void removeFromCart(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int transactionId = Integer.parseInt(request.getParameter("id"));
        transactionDao.deleteTransaction(transactionId);
        response.sendRedirect(request.getContextPath() + "/cart/list");
    }

    private void checkout(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 这里可以添加结算逻辑
        response.sendRedirect(request.getContextPath() + "/cart/list");
    }
} 